package com.zjs;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactory;

import javax.jms.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Producer {
    // 从配置文件加载配置
    private final String brokerUrl;
    private final String topicName;
    private final String userName;
    private final String password;

    public Producer() {
        Properties props = new Properties();
        try {
            InputStream input = getClass().getClassLoader().getResourceAsStream("application.properties");
            if (input == null) {
                throw new FileNotFoundException("配置文件 application.properties 未找到");
            }
            props.load(input);
        } catch (IOException e) {
            throw new RuntimeException("加载配置文件失败", e);
        }
        this.brokerUrl = props.getProperty("activemq.brokerUrl");
        this.topicName = props.getProperty("activemq.topicName");
        this.userName = props.getProperty("activemq.userName");
        this.password = props.getProperty("activemq.password");
        if (this.brokerUrl == null || this.topicName == null) {
            throw new IllegalArgumentException("配置项缺失");
        }
    }

    public void producer() {
        PooledConnectionFactory pooledConnectionFactory = null;
        Connection connection = null;
        Session session = null;
        try {
            // 创建基础连接工厂
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, brokerUrl);
            // 使用连接池包装连接工厂
            pooledConnectionFactory = new PooledConnectionFactory(connectionFactory);
            // 获取连接
            connection = pooledConnectionFactory.createConnection();
            // 启动连接
            connection.start();
            // 创建Session
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            // 创建topic
            Topic topic = session.createTopic(topicName);
            // 创建消息生产者
            MessageProducer producer = session.createProducer(topic);
            // 设置持久化
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            // 创建消息
            TextMessage message = session.createTextMessage("Hello World");
            // 发送消息
            producer.send(message);
            System.out.println("发送消息：" + message.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        new Producer().producer();
    }

}